package com.tjh.springbootapi.controller;

import com.koala.apiprototype.annotations.IgnoreValidate;
import com.koala.apiprototype.db.KeyGenerator;
import com.koala.apiprototype.utils.security.PasswordUtils;
import com.koala.apiprototype.utils.security.VerificationCodeUtils;
import com.koala.apiprototype.web.response.ApiException;
import com.koala.apiprototype.web.response.ExceptionCode;
import com.koala.apiprototype.web.response.RawResponse;
import com.tjh.springbootapi.config.ApiRequestContext;
import com.tjh.springbootapi.entity.Sysuser;
import com.tjh.springbootapi.service.SysuserService;
import com.tjh.springbootapi.view.LoginSysuser;
import com.tjh.springbootapi.view.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller
 * Generated on 2020-03-22
 */
@RestController
@RequestMapping("/sysuser")
public class SysuserController {

    @Autowired
    private SysuserService sysuserService;

    /*@Autowired
    private RedisStringService redisStringService;*/

    //密码最小长度
    @Value("8")
    private Integer passwordMinLength;

    //密码复杂度，可选值1-4，表示大小字母、小写、数字、特殊字符1-4种组合
    @Value("4")
    private Integer passwordComplexity;

    @Value("720")
    private Integer tokenExpireMinutes;

    /**
     * 按主键查询
     *
     * @param id 主键Id
     * @return 实体
     */
    @GetMapping("/find/{id}")
    public Sysuser find(@PathVariable(value = "id") String id) {
        return sysuserService.findById(id);
    }

    /**
     * 新增用户
     *
     * @param sysuser
     * @return
     */
    @IgnoreValidate
    @PostMapping("/saveSysuser")
    public String saveSysuser(@RequestBody Sysuser sysuser) {
        return sysuserService.saveSysuser(sysuser);
    }

    @IgnoreValidate
    @PostMapping("/login")
    public UserToken login(@RequestBody LoginSysuser request) {
        if (StringUtils.isEmpty(request.getUserName()) || StringUtils.isEmpty(request.getPassWord()) || StringUtils.isEmpty(request.getVerifyCode())) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode());
        }
        if (!VerificationCodeUtils.validate(ApiRequestContext.get().getRequest().getSession().getId(), request.getVerifyCode())) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "验证码错误");
        }
        boolean isPasswordValid = PasswordUtils.isValid(request.getPassWord(), passwordMinLength, passwordComplexity);
        Sysuser user = sysuserService.login(request.getUserName(), request.getPassWord());
        return buildUserToken(user, isPasswordValid);
    }

    private UserToken buildUserToken(Sysuser user, boolean isPasswordValid) {
        UserToken userToken = new UserToken();
        String token = KeyGenerator.genId();
        userToken.setToken(token);
        userToken.setUserId(user.getId());
        userToken.setUserName(user.getUserName());
        userToken.setPwdValid(isPasswordValid ? "1" : "0");

        //redisStringService.setValue(ApiConstants.REDIS_KEY_USER_TOKEN_PREFIX + token, tokenExpireMinutes, TimeUnit.MINUTES);
        return userToken;
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @RawResponse
    @IgnoreValidate
    @GetMapping("/getVerificationCode")
    public String getVerificationCode() {
        String sessionId = ApiRequestContext.get().getRequest().getSession().getId();
        String base64 = VerificationCodeUtils.generateExpression(sessionId, 160, 40);
        return "data:image/png;base64," + base64;
    }
}



